package product

import (
	"OnlineRetailers/controllers/admin/PageNum"
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type GetProduct struct {
	beego.Controller
}

func (c *GetProduct) GetProduct() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/Product/GetProduct"
	res := resMes.GetProductDetaileds{}
	productDetailed := []*Admin.ProductDetailed{}
	log := &error2.Log{}
	var err error
	o := orm.NewOrm()
	Page, err := c.GetInt("Page", 0)
	//fmt.Println(Page)
	add, err := c.GetInt("add", -1)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	begin, err := c.GetInt("begin", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	if add == 0 {
		err = session2.CheckSession(c.Ctx.Request.Header["Session"], 1)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	var sql string
	//fmt.Println(begin)
	if add == -1 {
		//fmt.Println(1111)
		count, err := PageNum.GetPageNum("product_detailed", o)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, "GetPageNum"+err.Error())
			return
		}
		res.Count = count / models.AdminPage
		sql = "select * from `product_detailed` order by `product_id` desc limit ? offset ?"
		_, err = o.Raw(sql, models.AdminPage, models.AdminPage*Page).QueryRows(&productDetailed)
	} else {
		if add == 0 {
			sql = "select * from `product_detailed` order by `product_id` desc limit ?,?"
		} else if add == 1 {
			sql = "select * from `product_detailed` order by `sales` desc  limit ?,?"
		}
		_, err = o.Raw(sql, begin, begin+models.DateLengthByProduct).QueryRows(&productDetailed)
	}

	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	sql = "select * from `classification_product_detaileds` left join `classification` on `classification`.`classification_id`=`classification_product_detaileds`.`classification_id` where `classification_product_detaileds`.`product_detailed_id`=?"
	for i := 0; i < len(productDetailed); i++ {

		_, err = o.Raw(sql, productDetailed[i].ProductId).QueryRows(&productDetailed[i].Classification)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}

	res.ProductDetailed = productDetailed
	res.Code = "200"
	c.Data["json"] = res

}
